import 'dart:io';
import 'package:at_utils/at_logger.dart';

const String workingDirectory = '../../packages/at_onboarding_cli';
const Duration enrollmentTimeout = Duration(seconds: 180);

final logger = AtSignLogger('AtOnboardingFunctionalTestsProxy');

Future<bool> submitEnrollmentRequest(String otp, String atSign, String deviceId, String keyFile, String rootServer, String appName, String namespaces) async {
  logger.info('Submitting enrollment request for $atSign with device ID: $deviceId');

  String enrollCommand = 'dart run bin/activate_cli.dart enroll -s $otp -a $atSign --rootServer $rootServer -d $deviceId -n "$namespaces" --app $appName --keys $keyFile';
  logger.info('Executing command: $enrollCommand');
  List<String> enrollParts = enrollCommand.split(' ');

  List<String> processedParts = [];
  bool inQuotes = false;
  String currentPart = '';

  for (String part in enrollParts) {
    if (part.startsWith('"') && part.endsWith('"')) {
      processedParts.add(part.substring(1, part.length - 1));
    } else if (part.startsWith('"')) {
      inQuotes = true;
      currentPart = part.substring(1);
    } else if (part.endsWith('"') && inQuotes) {
      currentPart += ' $part';
      processedParts.add(currentPart.substring(0, currentPart.length - 1));
      inQuotes = false;
      currentPart = '';
    } else if (inQuotes) {
      currentPart += ' $part';
    } else {
      processedParts.add(part);
    }
  }

  logger.info('Executing enrollment command: ${processedParts.join(' ')}');

  ProcessResult result = await Process.run(
    processedParts[0],
    processedParts.skip(1).toList(),
    workingDirectory: workingDirectory,
  ).timeout(enrollmentTimeout);

  logger.info('Enrollment command exit code: ${result.exitCode}');
  logger.info('Enrollment command stdout: ${result.stdout}');
  logger.info('Enrollment command stderr: ${result.stderr}');

  if (result.exitCode == 0) {
    logger.info('✓ Enrollment request submitted successfully');
    return true;
  } else {
    String stderr = result.stderr.toString();
    String stdout = result.stdout.toString();

    if (stderr.contains('enrollment') && (stderr.contains('pending') || stderr.contains('waiting')) ||
        stdout.contains('enrollment') && (stdout.contains('pending') || stdout.contains('waiting'))) {
      logger.info('✓ Enrollment request submitted and is pending approval');
      return true;
    }

    if (stderr.contains('AT0023') || stderr.contains('Waited for') || stderr.contains('millis')) {
      logger.info('✓ Enrollment request submitted but timed out waiting for approval');
      return true;
    }

    if (stderr.contains('unable to connect') || stderr.contains('AT0021')) {
      logger.warning('⚠ Connection issue during enrollment - may need to retry or check proxy');
      return false;
    }

    logger.warning('✗ Enrollment request failed: $stderr');
    return false;
  }
}